<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="8" :md="6" :lg="6" :xl="5">
        <el-card class="user-card">
          <div class="user-profile">
            <div class="avatar-wrapper">
              <el-avatar :size="120" :src="userInfo.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
              <el-upload
                class="avatar-uploader"
                action="#"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
              >
                <div class="update-overlay">
                  <i class="el-icon-camera"></i>
                </div>
              </el-upload>
            </div>
            <h3 class="user-name">{{ userInfo.name }}</h3>
            <p class="user-role">{{ userInfo.nickname }}</p>
            <div class="user-stats">
              <div class="stat-item">
                <div class="stat-value">{{ userInfo.deptName || '研发部' }}</div>
                <div class="stat-label">所属部门</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ userInfo.jobTitle || '工程师' }}</div>
                <div class="stat-label">职位</div>
              </div>
            </div>
          </div>
          <div class="menu-list">
            <div
              :class="['menu-item', activeTab === 'profile' ? 'active' : '']"
              @click="activeTab = 'profile'"
            >
              <i class="el-icon-user"></i>
              <span>个人信息</span>
            </div>
            <div
              :class="['menu-item', activeTab === 'account' ? 'active' : '']"
              @click="activeTab = 'account'"
            >
              <i class="el-icon-lock"></i>
              <span>账户管理</span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="16" :md="18" :lg="18" :xl="19">
        <!-- 个人信息面板 -->
        <el-card v-if="activeTab === 'profile'" class="content-card">
          <div slot="header" class="content-header">
            <span>个人信息</span>
            <el-button
              v-if="!isEditing"
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="startEditing"
            >
              编辑
            </el-button>
          </div>
          <div v-if="!isEditing" class="user-info">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="info-item">
                  <div class="info-label">
                    <i class="el-icon-user"></i>
                    <span>姓名</span>
                  </div>
                  <div class="info-value">{{ userInfo.name || '未设置' }}</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <div class="info-label">
                    <i class="el-icon-male"></i>
                    <span>性别</span>
                  </div>
                  <div class="info-value">{{ userInfo.gender === 1 ? '男' : userInfo.gender === 2 ? '女' : '未设置' }}</div>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="info-item">
                  <div class="info-label">
                    <i class="el-icon-chat-dot-square"></i>
                    <span>昵称</span>
                  </div>
                  <div class="info-value">{{ userInfo.nickname || '未设置' }}</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <div class="info-label">
                    <i class="el-icon-message"></i>
                    <span>邮箱</span>
                  </div>
                  <div class="info-value">{{ userInfo.email || '未设置' }}</div>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="info-item">
                  <div class="info-label">
                    <i class="el-icon-mobile-phone"></i>
                    <span>手机</span>
                  </div>
                  <div class="info-value">{{ userInfo.phone || '未设置' }}</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="info-item">
                  <div class="info-label">
                    <i class="el-icon-office-building"></i>
                    <span>地址</span>
                  </div>
                  <div class="info-value">{{ userInfo.address || '未设置' }}</div>
                </div>
              </el-col>
            </el-row>
            <div class="info-item-full">
              <div class="info-label">
                <i class="el-icon-document"></i>
                <span>个人介绍</span>
              </div>
              <div class="info-value introduction">{{ userInfo.introduction || '未设置' }}</div>
            </div>
          </div>
          <el-form
            v-else
            :model="editForm"
            :rules="rules"
            ref="editForm"
            label-width="80px"
            class="edit-form"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="editForm.name" placeholder="请输入姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="editForm.gender" placeholder="请选择性别" style="width: 100%">
                    <el-option label="男" :value="1"></el-option>
                    <el-option label="女" :value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="昵称" prop="nickname">
                  <el-input v-model="editForm.nickname" placeholder="请输入昵称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="手机" prop="phone">
                  <el-input v-model="editForm.phone" placeholder="请输入手机号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="地址" prop="address">
                  <el-input v-model="editForm.address" placeholder="请输入地址"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="个人介绍" prop="introduction">
              <el-input
                type="textarea"
                v-model="editForm.introduction"
                placeholder="请输入个人介绍"
                :rows="4"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveUserInfo">保存</el-button>
              <el-button @click="cancelEdit">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <!-- 账户管理面板 -->
        <el-card v-if="activeTab === 'account'" class="content-card">
          <div slot="header" class="content-header">
            <span>账户管理</span>
          </div>
          <el-tabs>
            <el-tab-pane label="修改密码">
              <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="100px">
                <el-form-item label="当前密码" prop="oldPassword">
                  <el-input
                    type="password"
                    v-model="passwordForm.oldPassword"
                    placeholder="请输入当前密码"
                    show-password
                  ></el-input>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-input
                    type="password"
                    v-model="passwordForm.newPassword"
                    placeholder="请输入新密码"
                    show-password
                  ></el-input>
                </el-form-item>
                <el-form-item label="确认新密码" prop="confirmPassword">
                  <el-input
                    type="password"
                    v-model="passwordForm.confirmPassword"
                    placeholder="请确认新密码"
                    show-password
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="changePassword">修改密码</el-button>
                  <el-button @click="resetPasswordForm">重置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="安全设置">
              <div class="security-settings">
                <div class="security-item">
                  <div class="security-item-content">
                    <div class="security-icon"><i class="el-icon-mobile-phone"></i></div>
                    <div class="security-info">
                      <div class="security-title">手机绑定</div>
                      <div class="security-desc">已绑定手机：{{ userInfo.phone || '未绑定' }}</div>
                    </div>
                  </div>
                  <div class="security-action">
                    <el-button type="text" size="small">修改</el-button>
                  </div>
                </div>
                <div class="security-item">
                  <div class="security-item-content">
                    <div class="security-icon"><i class="el-icon-message"></i></div>
                    <div class="security-info">
                      <div class="security-title">邮箱绑定</div>
                      <div class="security-desc">已绑定邮箱：{{ userInfo.email || '未绑定' }}</div>
                    </div>
                  </div>
                  <div class="security-action">
                    <el-button type="text" size="small">修改</el-button>
                  </div>
                </div>
                <div class="security-item">
                  <div class="security-item-content">
                    <div class="security-icon"><i class="el-icon-lock"></i></div>
                    <div class="security-info">
                      <div class="security-title">账户密码</div>
                      <div class="security-desc">定期修改密码可以保护账户安全</div>
                    </div>
                  </div>
                  <div class="security-action">
                    <el-button type="text" size="small" @click="activeTab = 'account'">修改</el-button>
                  </div>
                </div>
                <div class="security-item">
                  <div class="security-item-content">
                    <div class="security-icon"><i class="el-icon-time"></i></div>
                    <div class="security-info">
                      <div class="security-title">登录记录</div>
                      <div class="security-desc">查看近期登录记录，保障账户安全</div>
                    </div>
                  </div>
                  <div class="security-action">
                    <el-button type="text" size="small">查看</el-button>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { selectById, update } from '@/api/emp'
import { getToken } from '@/utils/auth'

export default {
  name: 'UserCenter',
  data() {
    // 邮箱验证规则
    const validateEmail = (rule, value, callback) => {
      const emailRegex = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (value && !emailRegex.test(value)) {
        callback(new Error('邮箱格式不正确'))
      } else {
        callback()
      }
    }

    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      const phoneRegex = /^1[3-9]\d{9}$/
      if (value && !phoneRegex.test(value)) {
        callback(new Error('手机号格式不正确'))
      } else {
        callback()
      }
    }
    // 确认密码验证规则
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      activeTab: 'profile', // 当前激活的标签页
      isEditing: false,
      userInfo: {
        id: '',
        name: '小铭',
        gender: 1,
        nickname: '管理',
        email: 'pureAdmin@163.com',
        phone: '15888886789',
        address: '',
        introduction: '一个热爱开源的前端工程师',
        avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      },
      editForm: {
        id: '',
        name: '',
        gender: null,
        nickname: '',
        email: '',
        phone: '',
        address: '',
        introduction: '',
        avatar: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur' }
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' }
        ]
      },
      // 密码表单数据
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      // 密码表单验证规则
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入当前密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    // 获取用户信息
    getUserInfo() {
      // 模拟从后端获取数据
      // 真实环境应当从vuex或从后端获取当前登录用户的信息
      // const userId = this.$store.getters.userId
      // selectById(userId).then(response => {
      //   if (response.data.code === 1) {
      //     this.userInfo = response.data.data
      //   }
      // })
    },
    // 开始编辑
    startEditing() {
      this.editForm = { ...this.userInfo }
      this.isEditing = true
    },
    // 取消编辑
    cancelEdit() {
      this.isEditing = false
      this.$refs.editForm.resetFields()
    },
    // 保存用户信息
    saveUserInfo() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          // 模拟更新操作
          // 实际应调用API进行更新
          // update(this.editForm).then(response => {
          //   if(response.data.code === 1) {
          //     this.$message.success('个人信息更新成功')
          //     this.userInfo = { ...this.editForm }
          //     this.isEditing = false
          //   } else {
          //     this.$message.error(response.data.msg || '更新失败')
          //   }
          // })
          // 模拟成功更新
          this.userInfo = { ...this.editForm }
          this.isEditing = false
          this.$message.success('个人信息更新成功')
        }
      })
    },
    // 头像上传前的校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 自定义头像上传处理
    handleAvatarUpload(options) {
      // 模拟上传成功
      // 实际应使用文件上传API
      setTimeout(() => {
        // 模拟一个随机头像
        const avatars = [
          'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
          'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png',
          'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
        ]
        const randomAvatar = avatars[Math.floor(Math.random() * avatars.length)]
        this.userInfo.avatar = randomAvatar
        this.editForm.avatar = randomAvatar
        this.$message.success('头像更新成功')
      }, 1000)
    },
    // 修改密码
    changePassword() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          // 实际应调用API进行密码修改
          // 这里仅做模拟
          setTimeout(() => {
            this.$message.success('密码修改成功')
            this.resetPasswordForm()
          }, 1000)
        }
      })
    },
    // 重置密码表单
    resetPasswordForm() {
      this.$refs.passwordForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

// 左侧用户卡片样式
.user-card {
  margin-bottom: 20px;
  .user-profile {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
    .avatar-wrapper {
      position: relative;
      margin-bottom: 20px;
      .el-avatar {
        border: 4px solid rgba(255, 255, 255, 0.8);
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      }
      .update-overlay {
        position: absolute;
        bottom: 0;
        right: 0;
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background-color: #409EFF;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        cursor: pointer;
        transition: all 0.3s;
        &:hover {
          background-color: #66b1ff;
          transform: scale(1.1);
        }
      }
    }
    .user-name {
      font-size: 20px;
      font-weight: 600;
      margin: 0 0 5px;
      color: #303133;
    }
    .user-role {
      font-size: 14px;
      color: #909399;
      margin: 0 0 15px;
    }
    .user-stats {
      width: 100%;
      display: flex;
      justify-content: space-around;
      margin-top: 10px;
      padding: 15px 0;
      border-top: 1px solid #f0f0f0;
      .stat-item {
        text-align: center;
        .stat-value {
          font-size: 16px;
          font-weight: 600;
          color: #303133;
        }
        .stat-label {
          font-size: 12px;
          color: #909399;
          margin-top: 5px;
        }
      }
    }
  }
  .menu-list {
    margin-top: 10px;
    border-top: 1px solid #f0f0f0;
    .menu-item {
      display: flex;
      align-items: center;
      padding: 15px 20px;
      cursor: pointer;
      transition: all 0.3s;
      border-radius: 4px;
      i {
        margin-right: 10px;
        font-size: 18px;
        color: #909399;
      }
      span {
        font-size: 14px;
        color: #606266;
      }
      &:hover {
        background-color: #f5f7fa;
      }
      &.active {
        background-color: #ecf5ff;
        i, span {
          color: #409EFF;
        }
      }
    }
  }
}

// 右侧内容卡片样式
.content-card {
  .content-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    span {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
  .user-info {
    padding: 20px 0;
    .info-item {
      margin-bottom: 20px;
      .info-label {
        display: flex;
        align-items: center;
        margin-bottom: 5px;
        i {
          color: #409EFF;
          margin-right: 8px;
          font-size: 16px;
        }
        span {
          font-size: 14px;
          color: #909399;
        }
      }
      .info-value {
        padding: 0 0 0 24px;
        font-size: 14px;
        color: #303133;
      }
    }
    .info-item-full {
      margin-bottom: 20px;
      .info-label {
        display: flex;
        align-items: center;
        margin-bottom: 5px;
        i {
          color: #409EFF;
          margin-right: 8px;
          font-size: 16px;
        }
        span {
          font-size: 14px;
          color: #909399;
        }
      }
      .info-value {
        padding: 0 0 0 24px;
        font-size: 14px;
        color: #303133;
        &.introduction {
          white-space: pre-line;
          line-height: 1.6;
          padding: 10px 24px;
          background-color: #f5f7fa;
          border-radius: 4px;
        }
      }
    }
  }
  .edit-form {
    padding: 20px 0;
  }
  // 安全设置样式
  .security-settings {
    padding: 10px 0;
    .security-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px 0;
      border-bottom: 1px solid #f0f0f0;
      &:last-child {
        border-bottom: none;
      }
      .security-item-content {
        display: flex;
        align-items: center;
        .security-icon {
          width: 48px;
          height: 48px;
          border-radius: 50%;
          background-color: #ecf5ff;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;
          i {
            font-size: 24px;
            color: #409EFF;
          }
        }
        .security-info {
          .security-title {
            font-size: 16px;
            font-weight: 500;
            color: #303133;
            margin-bottom: 5px;
          }
          .security-desc {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }
}

// 响应式适配
@media (max-width: 768px) {
  .user-card {
    margin-bottom: 20px;
  }
}
</style>
